import matplotlib.pyplot as plt
import pandas as pd
import csv, os
def _append_to_csv(res_dict, taus, csv_path):
    import pandas as pd, os, csv
    header = ['strategy', 'tau', 'value']
    # 先读已存在的文件
    if os.path.isfile(csv_path):
        df = pd.read_csv(csv_path)
    else:
        df = pd.DataFrame(columns=header)

    # 用 dict 更新/插入
    new_rows = []
    for strat, vals in res_dict.items():
        for tau, val in zip(taus, vals):
            new_rows.append({'strategy': strat, 'tau': tau, 'value': val})
    new_df = pd.DataFrame(new_rows)

    # 以 (strategy,tau) 为键覆盖
    df = pd.concat([df, new_df]).drop_duplicates(
            subset=['strategy','tau'], keep='last')

    df.to_csv(csv_path, index=False)

def _plot_from_csv(csv_path, out_png, y_label):
    df = pd.read_csv(csv_path)
    # 同一 (strategy,tau) 如果有多行，取最后一次
    df = df.drop_duplicates(subset=['strategy','tau'], keep='last')
    # -----------------------------
    import matplotlib.pyplot as plt
    plt.figure(figsize=(6,4))
    for strat in df['strategy'].unique():
        sub = (df[df['strategy']==strat]
               .sort_values('tau'))
        plt.plot(sub['tau'], sub['value'],
                 marker='o', label=strat)
    plt.xlabel('tau (temperature)')
    plt.ylabel(y_label)
    plt.title(f'TSVM {y_label} vs. τ')
    plt.grid(True, alpha=.3)
    plt.legend()
    plt.tight_layout()
    plt.savefig(out_png, dpi=150)
    plt.close()


